/**
 * ShadowFileParser.java 16.06.2006
 */
package org.dicr.sys.linux;

import java.io.*;
import java.util.*;
import java.util.logging.*;

import org.dicr.util.data.*;
import org.dicr.util.data.exc.*;

/**
 * Shadow file parser
 * 
 * @author <A href='http://dicr.org'>Igor A Tarasov</A>
 * @version 060616
 */
public class ShadowFileParser {

	private static final Logger log = Logger.getLogger(ShadowFileParser.class.getName());

	/**
	 * Parse shadow file
	 * 
	 * @param in
	 *            input stream
	 * @return map user -> crypted password
	 * @throws IOException
	 */
	public static Map<String, String> parse(Reader in) throws IOException {
		if (in == null) throw new IllegalArgumentException("null input");
		Map<String, String> users = new HashMap<>();
		BufferedReader reader = new BufferedReader(in);
		while (true) {
			String line = reader.readLine();
			if (line == null) break;
			line = StringUtils.normalize(line);
			if (line == null || line.startsWith("#")) continue;
			String[] fields = line.split(":", 3);
			try {
				if (fields.length < 3) throw new FileFormatException(line);
				users.put(fields[0], fields[1]);
			} catch (Exception fex) {
				log.log(Level.WARNING, "error parsing shadow file line: " + line, fex);
			}
		}
		reader.close();
		return users;
	}
}
